package com.ita.os.merchant.web.controller;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;

import com.ita.os.merchant.exception.UserExistException;
import com.ita.os.merchant.po.Merchant;
import com.ita.os.merchant.service.MerchantService;
import com.ita.os.merchant.service.impl.MerchantServiceImpl;
import com.ita.os.merchant.util.WebUtils;
import com.ita.os.merchant.web.formbean.RegisterFormBean;

/**
 * Servlet implementation class RegisterServlet
 */
public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private MerchantService merchantService = new MerchantServiceImpl();
    public RegisterServlet() {
        super();
        
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		RegisterFormBean formbean = WebUtils.request2Bean(request, RegisterFormBean.class);
		if(formbean.validate() ==false){
			request.setAttribute("formbean", formbean);
			request.getRequestDispatcher("/WEB-INF/pages/register.jsp").forward(request, response);
			return;
		}
		Merchant merchant = new Merchant();
		try {
			BeanUtils.copyProperties(merchant, formbean);
			merchantService.addMerchant(merchant);
			 String message = String.format(
	                    "注册成功！！3秒后为您自动跳到登录页面！！<meta http-equiv='refresh' content='3;url=%s'/>", 
	                    request.getContextPath()+"/loginUi");
	            request.setAttribute("message",message);
	            request.getRequestDispatcher("/message.jsp").forward(request,response);
		}catch (UserExistException e) {
            formbean.getErrors().put("userName", "注册用户已存在！！");
            request.setAttribute("formbean", formbean);
            request.getRequestDispatcher("/WEB-INF/pages/register.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();             
            request.setAttribute("message", "对不起，注册失败！！");
            request.getRequestDispatcher("/message.jsp").forward(request,response);
        }
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
